package com.itheima.controller;

import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.itheima.pojo.Result;
import com.itheima.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
public class UploadController {

    @Autowired
    AliOSSUtils aliOSSUtils;

    @PostMapping("/upload1")
    public Result upload(String username, Integer age, MultipartFile image) throws IOException {
        log.info("文件上传：username:{}, age:{}, image:{}", username, age, image.getOriginalFilename());
        // 获取原始文件名
        String originalFilename = image.getOriginalFilename();

        // 构造唯一的文件名
        String newFilename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        // 将文件转存在电脑的某个目录下
        image.transferTo(new File("D:\\UploadFile\\" + newFilename));

        return Result.success();
    }

    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        log.info("文件上传：{}", image.getOriginalFilename());

        // 调用阿里云工具类上传文件
        String ossUrl = aliOSSUtils.upload(image);

        // 打印上传成功的ossUrl
        log.info("上传成功：{}", ossUrl);

        // 返回上传成功后的ossUrl
        return Result.success(ossUrl);
    }
}
